<?php
namespace App\Http\Controllers;
/**
 * Created by PhpStorm.
 * User: zyt
 * Date: 2016/9/8
 * Time: 14:40
 * 爸妈问答评论
 */
use App\Common\DemandSW;
use App\Http\Controllers\CheckController;
use App\QuestionComments;
use App\Question;
use App\QuestionPraise;
use App\User;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class QuestionCommentsController extends CheckController {
    public function __construct( Request $request) {
        if($request->input('token') != 'sys'){
            parent::__construct($request);
        }
    }

    // 评论列表获取
    public function getIndex(Request $request) {
        $question_id = $request->input('question_id', '');
        $perpage = $request->input('perpage', 10);
        $next_cursor = $request->input('next_cursor', 1);
        $from = $request->input('from', '');
        $sort = $request->input('sort', 'hot'); // 评论楼层排序规则 desc 时间倒序 hot 热度排序（楼内评论数以及点赞数最多）
        $isadmin = false;
        if ($question_id) {
            $commarr = [];
            if ($this->userinfo && $this->userinfo->id == 1) {
                $isadmin = true;
            }
            $rootcomments = QuestionComments::where('question_id', $question_id)
                ->where('floor_reply', null)
                ->orderBy('recommend', 'desc');
            if ($sort == 'hot') {
                $rootcomments->select('*',DB::raw('IFNULL(praisenum,0) as totalnum'))
                    ->orderBy('totalnum', 'desc');
            }
            if ($from != 'xcx') {
                $rootcomments->where('type', 1);
            }
            $rootcomments = $rootcomments->orderBy('created_at', 'desc')
                ->skip(($next_cursor -1)* $perpage)
                ->take($perpage)
                ->get();

            // 2.根据根回复进行相关所有回复查询，包括根回复和楼内回复
            if (count($rootcomments)) {
                $rcarr = array();
                foreach ($rootcomments as &$qc) {
                    $rcarr[] = $qc->bamaso_id;
                    if ($this->userinfo) {
                        $quespraise = QuestionPraise::where('qc_id', $qc->id)->where('user_id', $this->userinfo->id)->first();
                        $qc->pid = $quespraise ? $quespraise->id : null;
                    } else {
                        $qc->pid = null;
                    }
                    if ($qc->owner_hidden) {
                        $qc->nickname = '匿名用户';
                        $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                    } else {
                        $user = User::find($qc->user_id);
                        if ($user) {
                            $qc->nickname = $user->nickname;
                            $qc->face_img = $user->avatarurl;
                        } else {
                            $qc->nickname = '匿名用户';
                            $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                        }
                    }
                    $qc->title = $this->replace($qc->title);
                    $qc->content = $this->replace($qc->content);
                    $qc->created_at_str = date("m月d日 H:i", strtotime($qc->created_at));
                    $quesarr[] = $qc->bamaso_id;
                    $commidarr[$qc->bamaso_id][] = $qc->bamaso_id;
                    $commarr[$qc->bamaso_id][] = $qc;
                }
                $quescomments = QuestionComments::whereIn('root_reply', $rcarr)
//                    ->where('ishidden', 0)
                    ->orderBy('recommend', 'desc')
                    ->orderBy("created_at", "asc");
                if ($from != 'xcx') {
                    $quescomments->where('type', 1);
                }
                $quescomments = $quescomments->get();
                foreach ($quescomments as &$qc) {
                    if (empty($qc->floor_reply)) {              // 根评论
                        // $quespraise = QuestionPraise::where('qc_id', $qc->id)->where('user_id', $this->userinfo->id)->first();
                        // $qc->pid = $quespraise ? $quespraise->id : null;
                        // if ($qc->owner_hidden) {
                        //     $qc->nickname = '匿名用户';
                        //     $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                        // } else {
                        //     $user = User::find($qc->user_id);
                        //     if ($user) {
                        //         $qc->nickname = $user->nickname;
                        //         $qc->face_img = ImageUrl::face("user", $user->bamaso_id);
                        //     } else {
                        //         $qc->nickname = '匿名用户';
                        //         $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                        //     }
                        // }
                        // $qc->title = $this->replace($qc->title);
                        // $qc->content = $this->replace($qc->content);
                        // $qc->created_at_str = date("m月d日 H:i", strtotime($qc->created_at));
                        // $quesarr[] = $qc->bamaso_id;
                        // $commidarr[$qc->bamaso_id][] = $qc->bamaso_id;
                        // $commarr[$qc->bamaso_id][] = $qc;
                    } else {                                // 楼内评论
                        if (in_array($qc->floor_reply, $quesarr)) {
                            $backcomments = QuestionComments::where('bamaso_id', $qc->floor_reply)->first();
                            if ($backcomments->owner_hidden) {
                                $qc->backusernick = '匿名用户';
                            } else {
                                $backuser = User::find($backcomments->user_id);
                                $qc->backusernick = ($backuser && $backuser->nickname) ? $backuser->nickname : '爸妈搜用户';
                            }
                            if ($qc->owner_hidden) {
                                $qc->nickname = '匿名用户';
                                $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                            } else {
                                $user = User::find($qc->user_id);
                                if ($user) {
                                    $qc->nickname = $user->nickname;
                                    $qc->face_img = $user->avatarurl;
                                } else {
                                    $qc->nickname = '匿名用户';
                                    $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                                }
                            }
                            $qc->title = $this->replace($qc->title);
                            $qc->content = $this->replace($qc->content);
                            $qc->created_at_str = date("m月d日 H:i", strtotime($qc->created_at));
                            $commarr[$qc->root_reply][] = $qc;
                            $commidarr[$qc->root_reply][] = $qc->bamaso_id;
                        } else {
                            foreach ($commidarr as $key => $value) {
                                if (in_array($qc->floor_reply, $value)) {
                                    $backcomments = QuestionComments::where('bamaso_id', $qc->floor_reply)->first();
                                    if ($backcomments->owner_hidden) {
                                        $qc->backusernick = '匿名用户';
                                    } else {
                                        $backuser = User::find($backcomments->user_id);
                                        $qc->backusernick = ($backuser && $backuser->nickname) ? $backuser->nickname : '爸妈搜用户';
                                    }
                                    if ($qc->owner_hidden) {
                                        $qc->nickname = '匿名用户';
                                        $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                                    } else {
                                        $user = User::find($qc->user_id);
                                        if ($user) {
                                            $qc->nickname = $user->nickname;
                                            $qc->face_img = $user->avatarurl;
                                        } else {
                                            $qc->nickname = '匿名用户';
                                            $qc->face_img = 'http://source.bamasoso.com/resources/h5/question_pic.png/app';
                                        }
                                    }
                                    $qc->title = $this->replace($qc->title);
                                    $qc->content = $this->replace($qc->content);
                                    $qc->created_at_str = date("m月d日 H:i", strtotime($qc->created_at));
                                    $commarr[$qc->root_reply][] = $qc;
                                    $commidarr[$qc->root_reply][] = $qc->bamaso_id;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            $data = [
                'quescomments' => $commarr,
                'has_more' => count($rootcomments) == $perpage,
                'next_cursor' => $next_cursor + 1,
                'isadmin' => $isadmin
            ];
            return $this->output(200, "评论获取成功！", $data);
        } else {
            return $this->output(201, "评论获取失败！");
        }
    }

    // 问答评论点赞/取消赞
    public function postPraise(Request $request){
        $qc_id = $request->input('qc_id', '');
        if ($qc_id) {
            $praise = QuestionPraise::where('qc_id', $qc_id)->where('user_id', $this->userinfo->id)->first();
            if ($praise) {
                $praise->delete();
                QuestionComments::where('id', $qc_id)->decrement('praisenum', 1);
            } else {
                $praise = new QuestionPraise();
                $praise->qc_id = $qc_id;
                $praise->user_id = $this->userinfo->id;
                $praise->save();
                QuestionComments::where('id', $qc_id)->increment('praisenum', 1);
            }
            return $this->output(200, "点赞成功！");
        }
        return $this->output(201, "点赞失败！");
    }

    // 添加评论
    public function postAdd(Request $request) {
        if ($request->input('question_id', '')) {
            $qc = new QuestionComments();
            $type = $request->input('type', '1');
            $qc->type = $type;
            if ($type == '1') {//文字
                if ($request->input('content', '')) {
                    // 判断是否含有敏感词
                    $content = $request->input('content');

                    if (DemandSW::haveSV($content) > 0) {
                        return $this->output(203, '含有敏感词');
                    }

                    $qc->content = $content;
                } else {
                    return $this->output(202, "内容不能为空");
                }
            } elseif ($type == '2' || $type == '3') {//2.录音3图片
                $file = $request->file('file');
                if (isset($file) && $file) {
                    $ext = $file->getClientOriginalExtension();
                    $filename = $this->getTimestamp(12).'.'.$ext;
                    $filename_str = 'xcx/comments/'.$filename;
                    $this->storeFile( $file, $filename_str);
                    $qc->content =  "https://apissources.bamasoso.com/".$filename_str;
                } else {
                    $qc->content = '';
                }
                if ($type == '2' && $request->input('time','')) {
                    $qc->time = $request->input('time');
                }
            }
            $qc->question_id = $request->question_id;
            $qc->floor_reply = $request->input('floor_reply');
            $qc->owner_hidden = $request->input('owner_hidden', 0);
            $qc->user_id = $this->userinfo->id;
            $qc->imgurl = $request->input('url');
            $qc->save();
            $hashids = new Hashids(env('APP_KEY', 'JfMdiJeoEcrAiKsY60EldxLkGcI2gF9i'), 10);
            $id = $hashids->encode($qc->id);
            $qc->bamaso_id = 'qc'.$id;
            if ($qc->floor_reply) {
                $qc->root_reply = $request->input('root_reply');
            } else {
                $qc->root_reply = 'qc'.$id;
            }
            $qc->save();
            $backcomments = QuestionComments::where('bamaso_id', $qc->floor_reply)->first();
            if ($backcomments) {
                $backuser = User::find($backcomments->user_id);
                if ($backuser) {
                    $qc->backusernick = $backuser->nickname ? $backuser->nickname : '用户';
                } else {
                    $qc->backusernick = '用户';
                }
            }
            $qc->nickname = $this->userinfo->nickname ? $this->userinfo->nickname : '用户';
            $qc->face_img = $this->userinfo->avatarurl ? $this->userinfo->avatarurl : 'https://apissources.bamasoso.com/xcx/comment/user_img.png';
            $qc->created_at_str = date("m月d日 H:i", strtotime($qc->created_at));
            $qc->pid = null;
            $qc->praisenum = "0";
            $qc->recommend = "0";
            $qc->time_s = $request->input('time','')?ceil(($request->input('time'))/1000): 0;  //用于页面显示的总秒数
//            Question::where('bamaso_id', $qc->question_id)->increment('comments', 1);
            // 评论成功后给提问者推送'新评论模板' 暂注
            return $this->output(200, "评论成功！", $qc);
        }
        return $this->output(201, "参数错误");
    }

    // 管理员删除评论
    public function postadminDelete(Request $request) {
        $id = $request->input('bamaso_id', '');
        $questionid = $request->input('question_id', '');
        if ($id && $questionid) {
            if ($this->userinfo->id == 1) {
                QuestionComments::where('root_reply', $id)->delete();
                return $this->output(200, "为民除害成功！", '');
            } else {
                return $this->output(202, "非法操作，说，你是怎么进来的！", '');
            }
        } else {
            return $this->output(201, "那个，问题走丢了，不用删了");
        }
    }

    // 管理员置顶评论、取消置顶评论
    public function postadminUp(Request $request) {
        $id = $request->input('bamaso_id', '');
        // type：up置顶 down取消置顶
        $recommend = $request->input('recommend', 0);

        if ($id) {
            if ($this->userinfo->id == 1) {
                if ($recommend == 0) {
                    QuestionComments::where('bamaso_id', $id)->update(['recommend' => 1]);
                    $str = '置顶成功！';
                    $backrecommend = 1;
                } else {
                    QuestionComments::where('bamaso_id', $id)->update(['recommend' => 0]);
                    $str = '取消置顶成功！';
                    $backrecommend = 0;
                }
                return $this->output(200, $str, $backrecommend);
            } else {
                return $this->output(202, "非法操作，说，你是怎么进来的！", '');
            }
        } else {
            return $this->output(201, "非法操作");
        }
    }

    // 管理员置顶评论、取消置顶评论
    public function postadminHidden(Request $request) {
        $id = $request->input('bamaso_id', '');
        if ($id) {
            if ($this->userinfo->id == 1) {
                QuestionComments::where('bamaso_id', $id)->update(['ishidden' => 1]);
                return $this->output(200, '操作成功', '');
            } else {
                return $this->output(202, "非法操作，说，你是怎么进来的！", '');
            }
        } else {
            return $this->output(201, "非法操作");
        }
    }

    public function replace ($str) {
        $pattern1='/\[bms([^\]e]*)\]/';
        $pattern2='/\[bms(emoji[^\]]*)\]/';
        $str = preg_replace($pattern1, "<img src='https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/\${1}'>", $str);
        $str = preg_replace($pattern2, "<img src='http://source.bamasoso.com/bmsui/emoji/\${1}/wm'>", $str);
        return $str;
    }
    //七牛  存储
    private function storeFile($file, $filename) {
        $disk = QiniuStorage::disk('qiniu');
        $disk->put($filename, file_get_contents( $file->getRealPath()));
        $url = explode("?",$disk->downloadUrl($filename))[0];
        return $url;
    }
    //获取时间戳
    public function getTimestamp($digits = false) {
        $digits = $digits > 10 ? $digits : 10;
        $digits = $digits - 10;
        if ((!$digits) || ($digits == 10))
        {
            return time();
        } else {
            return number_format(microtime(true),$digits,'','');
        }
    }
}
